#include "PolFile.hpp"
#include <fstream>
#include "PolyMesh.hpp"

using namespace std;

bool PolFile::Read(const std::string& aFile,
                   PolyMesh&          aMesh)
{
   aMesh.Clear();
   ifstream file(aFile.c_str());
   std::string identifier;
   if (!(file >> identifier && identifier == "poly"))
   {
      return false;
   }

   int vertCount, polycount;
   file >> vertCount >> polycount;
   aMesh.verts.resize(vertCount);
   for (int i = 0; i < vertCount; ++i)
   {
      Vec3& v = aMesh.verts[i];
      file >> v[0] >> v[1] >> v[2];
   }

   for (int i = 0; i < polycount; ++i)
   {
      Polyhedron p;
      file >> p.arity;
      assert(p.arity == 4 || p.arity == 6);
      for (int j = 0; j < p.arity; ++j)
      {
         file >> p.vertex[j];
      }
      file >> p.material;
      aMesh.polys.push_back(p);
   }
   aMesh.Recompute();
   aMesh.Updated();
   return true;
}

bool PolFile::Write(const std::string& aFile,
                    const PolyMesh&    aMesh)
{
   ofstream io(aFile.c_str());
   std::string identifier;
   io << "poly" << '\n';
   const PolyhedronList& polys = *aMesh.polys;
   
   io << aMesh.verts.size() << ' ' << polys.size() << '\n';
   for (size_t i = 0; i < aMesh.verts.size(); ++i)
   {
      const Vec3& v = aMesh.verts[i];
      io << v[0] << ' ' << v[1] << ' ' << v[2] << '\n';
   }

   for (size_t i = 0; i < polys.size(); ++i)
   {
      const Polyhedron& p = polys[i];
      io << p.arity << "  ";
      for (int j = 0; j < p.arity; ++j)
      {
         io << p.vertex[j] << ' ';
      }
      io << ' ' << p.material;
      io << '\n';
   }
   return true;
}
